package com.android;

import android.app.Application;

import com.android.net.OkGo;
import com.android.net.cookie.CookieJarImpl;
import com.android.net.cookie.store.DBCookieStore;
import com.android.net.https.HttpsUtils;
import com.android.net.interceptor.HttpLoggingInterceptor;
import com.android.net.model.HttpHeaders;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;

/**
 * Created by leron on 2017/6/27.
 */

public class App extends Application {

    private static App app_instance;

    @Override
    public void onCreate() {
        super.onCreate();
        app_instance = this;
        initOkGo();


    }


    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    private void initOkGo() {

        OkHttpClient.Builder builder = new OkHttpClient.Builder();


            //log相关
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("Loan_data");
            loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);        //log打印级别，决定了log显示的详细程度
            loggingInterceptor.setColorLevel(Level.INFO);                               //log颜色级别，决定了log在控制台显示的颜色
            builder.addInterceptor(loggingInterceptor);                                 //添加默认debug日志

        //超时时间设置，默认60秒
        builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);      //全局的读取超时时间
        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);     //全局的写入超时时间
        builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);   //全局的连接超时时间

        //自动管理cookie（session的保持）
    //  builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)));            //使用sp保持cookie，如果cookie不过期，则一直有效
        builder.cookieJar(new CookieJarImpl(new DBCookieStore(this)));          //使用数据库保持cookie，如果cookie不过期，则一直有效
//        builder.cookieJar(new CookieJarImpl(new MemoryCookieStore()));          //使用内存保持cookie，app退出后，cookie消失

        //信任所有证书
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();
        builder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager);

        HttpHeaders headers = new HttpHeaders();
        headers.put("token", "123456789");

//        headers.put("clientTime", "1459845047000");
        // 其他统一的配置
        OkGo.getInstance().init(this)                           //调用初始化
                .setOkHttpClient(builder.build())//设置OkHttpClient
                .addCommonHeaders(headers)                      //全局head
                .setRetryCount(3);                              //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
    }

    public static App instance() {
        return app_instance;

    }


}
